package com.cy.metrics;

import com.codahale.metrics.*;
import com.cy.util.U;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;

import java.util.concurrent.*;

/**
 * @author yue.cao
 * @since 01-05-2021
 */
@Slf4j
public class ReporterDemo {


	@Test(description = "JMX reporter 综合练习 cmd --> jconsole  由于是testNg中运行的所以找org.testNg开头的")
	public void testJMXReporter() throws InterruptedException {
		log.error("===========START==============");
		MetricRegistry registry = new MetricRegistry();

		// ConsoleReporter reporter = ConsoleReporter
		// 		.forRegistry(registry)
		// 		.convertRatesTo(TimeUnit.SECONDS)
		// 		.convertDurationsTo(TimeUnit.SECONDS).build();
		// reporter.start(5, TimeUnit.SECONDS);

		JmxReporter jmxReporter = JmxReporter.forRegistry(registry)
				.convertRatesTo(TimeUnit.SECONDS)
				.convertDurationsTo(TimeUnit.SECONDS).build();
		jmxReporter.start();

		// CsvReporter csvReporter = CsvReporter.forRegistry(registry)
		// 		.formatFor(Locale.CHINA)
		// 		.convertRatesTo(TimeUnit.SECONDS)
		// 		.convertDurationsTo(TimeUnit.SECONDS)
		// 		.build(new File("G:\\giteeWorkspace\\LearnSomeThing\\target"));
		// csvReporter.start(5, TimeUnit.SECONDS);


		Slf4jReporter slf4jReporter = Slf4jReporter.forRegistry(registry)
				.withLoggingLevel(Slf4jReporter.LoggingLevel.WARN)
				.outputTo(log)
				.convertRatesTo(TimeUnit.SECONDS)
				.convertDurationsTo(TimeUnit.SECONDS)
				.build();
		slf4jReporter.start(5, TimeUnit.SECONDS);

		Counter total = new Counter();
		Counter success = new Counter();
		Counter fail = new Counter();
		RatioGauge successGauge = new RatioGauge() {
			@Override
			protected Ratio getRatio() {
				return Ratio.of(success.getCount(), total.getCount());
			}
		};

		Timer timer = new Timer();
		Histogram volumeHistogram = new Histogram(new ExponentiallyDecayingReservoir());
		registry.register("cy-total", total);
		registry.register("cy-success", success);
		registry.register("cy-fail", fail);
		registry.register("cy-successGauge", successGauge);
		registry.register("cy-timer", timer);
		registry.register("cy-volumeHistogram", volumeHistogram);

		while (true) {
			total.inc();
			volumeHistogram.update(ThreadLocalRandom.current().nextInt(1000));
			Timer.Context context = timer.time();
			try {
				int i = 1 / ThreadLocalRandom.current().nextInt(10);
				success.inc();
				U.sleepRandom();
			} catch (Exception e) {
				fail.inc();
			} finally {
				context.close();
			}


		}
	}
}
